# Install necessary packages

install.packages(cjoint, cregg, gtable, gridExtra, lemon, tidyverse, patchwork)

# Load packages for conjoint analysis.

library(cjoint)
library(cregg)

# Load packages for data visualization

library(tidyverse)
library(gtable)
library(gridExtra)
library(lemon)
library(patchwork)


# Define variables as factors with levels. Factor and level definition may be done upon import if desired.

chatbot_conjoint_data$age_range <- as.factor(chatbot_conjoint_data$age_range)
chatbot_conjoint_data$gender <- as.factor(chatbot_conjoint_data$gender)
chatbot_conjoint_data$education <- as.factor(chatbot_conjoint_data$education)
chatbot_conjoint_data$race <- as.factor(chatbot_conjoint_data$race)
chatbot_conjoint_data$hispanic <- as.factor(chatbot_conjoint_data$hispanic)
chatbot_conjoint_data$image_type <- as.factor(chatbot_conjoint_data$image_type)
chatbot_conjoint_data$image_race <- as.factor(chatbot_conjoint_data$image_race)
chatbot_conjoint_data$image_gender <- as.factor(chatbot_conjoint_data$image_gender)
chatbot_conjoint_data$match1 <- as.factor(chatbot_conjoint_data$match1)
chatbot_conjoint_data$g_match <- as.factor(chatbot_conjoint_data$g_match)
chatbot_conjoint_data$r_match <- as.factor(chatbot_conjoint_data$r_match)
chatbot_conjoint_data$pair_type <- as.factor(chatbot_conjoint_data$pair_type)

# For function `cj` to run correctly, columns must be factors and levels must be unique across factors. For example, `race` and `image_race` must have different level names.

chatbot_conjoint_data$gender <- recode_factor(chatbot_conjoint_data$gender, m = "M", f = "F", other = "Other")
chatbot_conjoint_data$education <- recode_factor(chatbot_conjoint_data$education, 'below high school' = "Below High School", 'high school diploma' = "High School", bachelors = "Bachelors", masters = "Masters", advanced = "Advanced")
chatbot_conjoint_data$race <- recode_factor(chatbot_conjoint_data$race, b = "R-Black", w="R-White", a="R-Asian", ai="R-American Indian", pi="R-Pacific Islander")
chatbot_conjoint_data$hispanic <- recode_factor(chatbot_conjoint_data$hispanic, hispanic = "Hispanic", 'non-hispanic' = "Non-Hispanic")
chatbot_conjoint_data$pair_type <- recode_factor(chatbot_conjoint_data$pair_type, 'h-c' = "Human-Chatbot", 'h-h' = "Human-Human", 'c-c' = "Chatbot-Chatbot")
chatbot_conjoint_data$image_type <- recode_factor(chatbot_conjoint_data$image_type, human = "Human", chatbot = "Chatbot")
chatbot_conjoint_data$image_race <- recode_factor(chatbot_conjoint_data$image_race, black = "Black", white = "White", asian = "Asian")
chatbot_conjoint_data$image_gender <- recode_factor(chatbot_conjoint_data$image_gender, male = "Male", female = "Female")
chatbot_conjoint_data$match1 <- recode_factor(chatbot_conjoint_data$match1, none = "No Match", one = "One Characteristic", two = "Two Characteristics")
chatbot_conjoint_data$g_match <- recode_factor(chatbot_conjoint_data$g_match, g_match_no = "No Gender Match", g_match_yes = "Gender Match")
chatbot_conjoint_data$r_match <- recode_factor(chatbot_conjoint_data$r_match, r_match_no = "No Race Match", r_match_yes = "Race Match")

# Assign factor labels for plotting.

attr(chatbot_conjoint_data$age_range, "label") <- "Respondent Age"
attr(chatbot_conjoint_data$gender, "label") <- "Respondent Gender"
attr(chatbot_conjoint_data$education, "label") <- "Respondent Education"
attr(chatbot_conjoint_data$race, "label") <- "Respondent Race"
attr(chatbot_conjoint_data$hispanic, "label") <- "Hispanic"
attr(chatbot_conjoint_data$image_type, "label") <- "Image Type"
attr(chatbot_conjoint_data$image_race, "label") <- "Image Race"
attr(chatbot_conjoint_data$image_gender, "label") <- "Image Gender"
attr(chatbot_conjoint_data$match1, "label") <- "Demographic Match"
attr(chatbot_conjoint_data$g_match, "label") <- "Gender Match"
attr(chatbot_conjoint_data$r_match, "label") <- "Race Match"
attr(chatbot_conjoint_data$pair_type, "label") <- "Choice Pair"

# Figure 1

chatbot_conjoint_data$preference_strength <- as.numeric(as.character(chatbot_conjoint_data$preference_strength)) #It may be necessary to convert this variable to numeric. 

# Create barplot for mean `preference_strength` for all preference data

bp_all <- chatbot_conjoint_data %>% 
  filter(race != 'R-Pacific Islander',
         race != 'R-American Indian') %>% 
  ggplot(aes(fill=r_preference, y = preference_strength, x = race)) +
  geom_bar(position = "dodge", stat = "summary", fun = "mean") +
  geom_text(aes(label = round(..y.., 3)), 
            position = position_dodge(width = 0.9), 
            stat = "summary", fun = "mean", vjust = 2,
            size = 3) +
  ggtitle("All Conjoint Profiles") +
  xlab("Respondent Race") + ylab("Preference") +
  theme(plot.title = element_text(hjust = 0.5)) + 
  labs(fill = "Race Preference")

  # Create barplot for mean `preference_strength` for all preference data subsetted by conjoint type

  bp_facet <- chatbot_conjoint_data %>% 
  filter(race != 'R-Pacific Islander', 
         race != 'R-American Indian') %>% 
  ggplot(aes(fill=r_preference, y = preference_strength, x = race)) +
  geom_bar(position="dodge", stat = "summary", fun = "mean") +
    geom_text(aes(label = round(..y.., 3)), 
            position = position_dodge(width = 0.9), 
            stat = "summary", fun = "mean", vjust = 2,
            size = 2) +
  ggtitle("Conjoint Profiles Subsetted by Pair Type") +
  xlab("Respondent Race") +
  ylab("Preference Strength") +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(fill = "Race Preference") +
  facet_wrap(vars(pair_type))

  # Arrange plots together using `patchwork` package

  bp_all + bp_facet + plot_layout(ncol = 1) # This produces Figure 1.


# AMCEs by `pair_type`; exclude `pair_type` from model as factor levels do not vary in human-human and chatbot-chatbot types.

stacked_amce <- cj(na.omit(chatbot_conjoint_data), response ~ age_range + education + race + hispanic + gender + image_race + image_gender + match1 + r_match + g_match, id = ~prolific_id, estimate = "amce", level_order = c("descending"), by = ~pair_type)

# Plot AMCEs subsetting by pair-type. This produces the basis for Figure 2.

stacked_amce_plot <- plot(stacked_amce, feature_headers = TRUE, xlab = "Estimated Average Marginal Component Effect (AMCE)", legend_pos = "none") +
  ggplot2::facet_wrap(~pair_type, nrow = 1L)

# The below code modifies the figure to remove NA column. 

gt_amce = ggplot_gtable(ggplot_build(stacked_amce_plot)) # Create gtable object of `stacked_amce_plot`
print(gt_amce)

gtable_show_names(gt_amce) # Show plot layout 

rm_grobs_amce <- gt_amce$layout$name %in% c("panel-4-1", "axis-t-4-1", # Remove everything related to panel four
                                            "strip-t-4-1", "axis-b-4-1",
                                            "axis-l-1-4", "axis-r-1-4",
                                            "ylab-r") 

gt_amce$grobs[rm_grobs_amce] <- NULL # Remove grobs
gt_amce$layout <- gt_amce$layout[!rm_grobs_amce, ] 

gtable_show_names(gt_amce) # Check results

names(gt_amce) # Remove the leftover space

gt_amce$widths

gt_amce$widths[15] = unit(.5, "cm")
gt_amce$widths[17] = unit(.5, "cm")

gtable_show_names(gt_amce)

grid.newpage() # Final side-by-side AMCE plot subsetted by `pair_type`. Figure 2.
grid.draw(gt_amce)

# Generate tabular regression results for `stacked_amce`. Results printed here populate the regression table in Appendix A1.

options(max.print=999999) #Increase max print
print(stacked_amce)

# create models for interaction between race and image_race. First model is for all data, the others are subsetted by pair_type.

race_int_all <- amce(response ~ age_range + education + race + hispanic + gender + image_type + image_race + image_gender + match1 + r_match + g_match + race:image_race, data = chatbot_conjoint_data, design = "uniform", respondent.varying = "race", respondent.id = "prolific_id", cluster = TRUE, na.ignore = FALSE, weights = NULL, baselines = NULL)

race_int_hc <- amce(response ~ age_range + education + race + hispanic + gender + image_type + image_race + image_gender + match1 + r_match + g_match + race:image_race, data = subset(chatbot_conjoint_data, pair_type=="Human-Chatbot"), design = "uniform", respondent.varying = "race" ,respondent.id = "prolific_id", cluster = TRUE, na.ignore = FALSE, weights = NULL, baselines = NULL)

race_int_hh <- amce(response ~ age_range + education + race + hispanic + gender + image_race + image_gender + match1 + r_match + g_match + race:image_race, data = subset(chatbot_conjoint_data, pair_type=="Human-Human"), design = "uniform", respondent.varying = "race" ,respondent.id = "prolific_id", cluster = TRUE, na.ignore = FALSE, weights = NULL, baselines = NULL)

race_int_cc <- amce(response ~ age_range + education + race + hispanic + gender + image_race + image_gender + match1 + r_match + g_match + race:image_race, data = subset(chatbot_conjoint_data, pair_type=="Chatbot-Chatbot"), design = "uniform", respondent.varying = "race" ,respondent.id = "prolific_id", cluster = TRUE, na.ignore = FALSE, weights = NULL, baselines = NULL)

plot(race_int_all, plot.display = "interaction", main = "ALL ACIE", xlab = "X AXIS TITLE GOES HERE")

# Produce ACIE plots for Figures 3 and 4.

plot(race_int_all, plot.display = "interaction", main = "ALL ACIE", xlab = "X AXIS TITLE GOES HERE") # This plot produces Figure 3.

# The below plots were generated separately and then combined manually to produce Figure 3. 

plot(race_int_hc, plot.display = "interaction", main = "HC Race Interaction Effects", xlab = "X AXIS TITLE GOES HERE")

plot(race_int_hh, plot.display = "interaction", main = "HH Race Interaction Effects", xlab = "X AXIS TITLE GOES HERE")

plot(race_int_cc, plot.display = "interaction", main = "CC Race Interaction Effects", xlab = "X AXIS TITLE GOES HERE")

# create models for interaction between gender and image_gender subsetted by pair-type. 

gender_int_hc <- amce(response ~ age_range + education + race + hispanic + gender + image_type + image_race + image_gender + match1 + r_match + g_match + gender:image_gender, data = subset(chatbot_conjoint_data, pair_type=="Human-Chatbot"), design = "uniform", respondent.varying = "gender" ,respondent.id = "prolific_id", cluster = TRUE, na.ignore = FALSE, weights = NULL, baselines = NULL)

gender_int_hh <- amce(response ~ age_range + education + race + hispanic + gender + image_race + image_gender + match1 + r_match + g_match + gender:image_gender, data = subset(chatbot_conjoint_data, pair_type=="Human-Human"), design = "uniform", respondent.varying = "gender" ,respondent.id = "prolific_id", cluster = TRUE, na.ignore = FALSE, weights = NULL, baselines = NULL)

gender_int_cc <- amce(response ~ age_range + education + race + hispanic + gender + image_race + image_gender + match1 + r_match + g_match + gender:image_gender, data = subset(chatbot_conjoint_data, pair_type=="Chatbot-Chatbot"), design = "uniform", respondent.varying = "gender" ,respondent.id = "prolific_id", cluster = TRUE, na.ignore = FALSE, weights = NULL, baselines = NULL)

# As above, plots were produced separately and then combined manually to produce the Figure in Appendix A2.

plot(gender_int_hc, plot.display = "interaction", main = "HC Gender Interaction Effects", xlab = "X AXIS TITLE GOES HERE")

plot(gender_int_hh, plot.display = "interaction", main = "HH Gender Interaction Effects", xlab = "X AXIS TITLE GOES HERE")

plot(gender_int_cc, plot.display = "interaction", main = "CC Gender Interaction Effects", xlab = "X AXIS TITLE GOES HERE")
